/* 
 * Created on 2005-2-7
 * Last modified on 2006-12-5
 * Powered by YeQiangWei.com
 */

package com.yeqiangwei.image;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;

import org.apache.log4j.Logger;

import com.yeqiangwei.tools.Arith;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


/**
 * @deprecated Use <code>ImageOperate_</code> instead.
 * @author yeqiangwei
 */
public class ImageOperate_ { 
	
	private static final Logger logger = 
		Logger.getLogger(ImageOperate.class.getName());
	
    Image img1;
    String message = "";
    String filePath = ""; //文件所在的根目录， 绝对路径。
    String waterImg1 = "", waterImg2=""; //水印图片文件名
    String waterPath = ""; //水印图片所在路径，绝对路径
    String str = new String("www.YeQiangWei.com");
    
    /**
     * 给图片加水印
     * @param oldFile 加水印前的文件名. 
     * @param newFile 加水印后的文件名。
     * @return
     */
    public void waterImage(String oldFile, String newFile){
    	filePath = filePath.replace("/", File.separator);
    	filePath = filePath.replace("\\", File.separator);
    	oldFile = oldFile.replace("/", File.separator);
    	newFile = newFile.replace("/", File.separator);
         try{
            File myFile = new File(filePath + oldFile); //指定文件名含路径
            Image src = javax.imageio.ImageIO.read(myFile); //构造Image对象 
            int w=src.getWidth(null); /* 得到源图宽 */  
            int h=src.getHeight(null); /* 得到源图高 */
            Graphics gim = src.getGraphics();
            BufferedImage tag = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);  
            tag.getGraphics().drawImage(src,0,0,w,h,null);
            if(!waterImg1.equals("") && waterImg2.equals("")){
                Image img1 = javax.imageio.ImageIO.read(new File(waterPath+waterImg1));//构造Image对象 
                int w1 = img1.getWidth(null); /* 得到水图1宽 */  
                int h1 = img1.getHeight(null); /* 得到水图1高 */
                tag.getGraphics().drawImage(img1,w-w1-12,h-h1-10,w1,h1,null);
            }
            if(!waterImg1.equals("") && !waterImg2.equals("")){
                Image img1 = javax.imageio.ImageIO.read(new File(waterPath+waterImg1));//构造Image对象 
                int w1 = img1.getWidth(null); //得到水图1宽  
                int h1 = img1.getHeight(null); //得到水图1高
                Image img2 = javax.imageio.ImageIO.read(new File(waterPath+waterImg2));//构造Image对象 
                    int w2 = img2.getWidth(null); //得到水图2宽  
                    int h2 = img2.getHeight(null); //得到水图2高   
                    //tag.getGraphics().drawImage(img2,w-w2-12,h-36,w2,h2,null);
                    //tag.getGraphics().drawImage(img1,w-w1-w2-16,h-36,w1,h1,null);
                    tag.getGraphics().drawImage(img2,w-w2-12,h-h2-10,w2,h2,null);
                    tag.getGraphics().drawImage(img1,w-w1-w2-12,h-h1-10,w1,h1,null);
            }
            FileOutputStream out=new FileOutputStream(filePath + newFile); //输出到文件流  
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
            encoder.encode(tag); //JPEG编码 
            gim.dispose();
            out.close();      
         }catch(Exception e){
             logger.error(e.toString());
         }    
    }
    
    /**
     * 往图片上写字 
     * @param oldFile 原图片路径
     * @param newFile 被写字后的图片路径
     * @param fontFamily 字体
     * @param fontSize 字号
     * @param right_x 距图片右边框宽度
     * @param down_y 距图片下边框高度
     * com.yeqiangwei.image
     */
    public void writeImage(String oldFile, String newFile
    		, String fontFamily, int fontSize
    		, int right_x, int down_y
    ){
    	if(right_x<1){
    		right_x = 10;
    	}
    	if(down_y<1){
    		down_y = 12;
    	}
    	filePath = filePath.replace("/", File.separator);
    	filePath = filePath.replace("\\", File.separator);
    	oldFile = oldFile.replace("/", File.separator);
    	newFile = newFile.replace("/", File.separator);
    	//设置字体
        if(fontFamily==null||fontFamily.trim().equals("")){
            fontFamily = "Tahoma";
        }
        if(fontSize<=0){
            fontSize = 12;
        }
        try{
            File myFile = new File(filePath + oldFile); //指定文件名含路径
            Image src = javax.imageio.ImageIO.read(myFile); //构造Image对象 
            int w=src.getWidth(null); //得到源图宽  
            int h=src.getHeight(null); //得到源图长
            //在你创立的image上写字
            Graphics gim = src.getGraphics();
            Font font = new Font(fontFamily, Font.BOLD, fontSize);
            gim.setFont(font);            
            gim.setColor(Color.black);
            gim.drawString(str, w-(str.length()*right_x-1), h-down_y);
            gim.setColor(Color.lightGray);
            gim.drawString(str, w-(str.length()*right_x-0), h-down_y-1);
            BufferedImage tag = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB); 
            tag.getGraphics().drawImage(src,0,0,w,h,null);
            FileOutputStream out=new FileOutputStream(filePath + newFile); //输出到文件流  
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
            encoder.encode(tag); //JPEG编码 
            gim.dispose();
            out.close();  
        }catch(Exception e){
            logger.error(e.toString());
        }
    } 
    
    
    /**
     * 切图and缩图
     * @param fileUrl 远程文件路径
     * @param filePathAndName 文件存放路径
     * @param w 缩放后宽
     * @param h 缩放后高
     * @param x 起始坐标
     * @param y 起始坐标
     * @param x_w 结束坐标
     * @param y_h  结束坐标
     * @return
     * com.yeqiangwei.image
     */
    public boolean drawImage(String fileUrl, String filePathAndName
    		, int w, int h
    		, int x, int y, int x_w, int y_h)
    {	
    	boolean bea = false;
        int ow = 0; /*指定的尺寸不在计算中变化*/
        int oh = 0; /*指定的尺寸不在计算中变化*/
        int x_ = x_w+x;
        int y_ = y_h+y;
		java.net.URL urlfile = null; 
		HttpURLConnection httpUrl = null; 
		BufferedInputStream bis = null;
		File f = new File(filePathAndName); 
		try{ 
			/* 连接指定的网络资源,获取网络输入流 */ 
			urlfile = new java.net.URL(fileUrl); 
			httpUrl = (HttpURLConnection)urlfile.openConnection(); 
			httpUrl.connect(); 
			bis = new BufferedInputStream(httpUrl.getInputStream()); 
		}catch(Exception e){ 
			logger.error(e.toString());
		} 
		try{ 
			Image img = javax.imageio.ImageIO.read(bis);
			ow = img.getWidth(null);
			oh = img.getHeight(null);
			/* 判断指定的坐标是否越界 */
			if(ow < x+x_w){
				x_ = ow;
				x = x_ - x_w;
			}
			if(oh < y_){
				y_ = oh;
				y = y_ - y_h;
			}
			if(x_-x > ow || y_-y > oh){
				x=0;
				y=0;
				x_=ow;
				y_=oh;
			}
			java.awt.image.BufferedImage tag
        		= new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);  
            Graphics g = tag.getGraphics();
            g.drawImage(img, 0, 0, w, h, x, y, x_, y_, null);
            FileOutputStream out=new FileOutputStream(f); /* 输出到文件流 */  
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
            encoder.encode(tag); /*JPEG编码*/ 
            out.flush();
            out.close();
            out = null;
            bea = true;
		}catch(Exception e){ 
			logger.error(e.toString());
		}finally{ 
			try{ 
				bis.close(); 
				httpUrl.disconnect(); 
			}catch(Exception e){ 
				logger.error(e.toString());
			} 
		}	
    	return bea;
    }
    
    /**
     * 
     * @param oldFile
     * @param newFile
     * @param w 缩放后宽
     * @param h 缩放后高
     * @param x 起始坐标
     * @param y 起始坐标
     * @param x_w 结束坐标
     * @param y_h  结束坐标
     * @return
     * com.yeqiangwei.image
     */
    public boolean inciseImage(String oldFile, String newFile
    		, int w, int h
    		, int x, int y, int x_w, int y_h)
    {	
    	boolean bea = false;
        int ow = 0; /*指定的尺寸不在计算中变化*/
        int oh = 0; /*指定的尺寸不在计算中变化*/
        int x_ = x_w+x;
        int y_ = y_h+y;
        File myFile = new File(oldFile); //指定文件名含路径
		try{ 
			Image img = javax.imageio.ImageIO.read(myFile);
			ow = img.getWidth(null);
			oh = img.getHeight(null);
			/* 判断指定的坐标是否越界 */
			if(ow < x+x_w){
				x_ = ow;
				x = x_ - x_w;
			}
			if(oh < y_){
				y_ = oh;
				y = y_ - y_h;
			}
			if(x_-x > ow || y_-y > oh){
				x=0;
				y=0;
				x_=ow;
				y_=oh;
			}
			java.awt.image.BufferedImage tag
        		= new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);  
            Graphics g = tag.getGraphics();
            g.drawImage(img, 0, 0, w, h, x, y, x_, y_, null);
            FileOutputStream out = new FileOutputStream(newFile); //输出到文件流  
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
            encoder.encode(tag); /*JPEG编码*/ 
            out.flush();
            out.close();
            out = null;
            g = null;
            tag = null;
            bea = true;
		}catch(Exception e){ 
			logger.error(e.toString());
		}	
    	return bea;
    }
    
    public String shrinkImage(int w, String oldFile, String newFile) throws IOException
    {
    	String str = null;
    	int h = 0;
        //final int ow = w; //指定的尺寸不在计算中变化
        final int oh = w; //指定的尺寸不在计算中变化
        double wd = 0; /* 宽度缩放比率 */
        double hd = 0; /* 高度缩放比率 */
        java.awt.image.BufferedImage tag;
        File myFile = new File(oldFile); //指定文件名含路径
        Image img = javax.imageio.ImageIO.read(myFile); //构造Image对象  
        int width = img.getWidth(null); //得到源图宽  
        int height = img.getHeight(null); //得到源图长
        if(w>width){
        	w = width;
        	h = height;
        }else{
            wd = Arith.div(w, width, 10); /* 计算出宽度的缩放比例 */
            /**
             * 按宽度缩放比率计算高度应缩放到的尺寸
             */
            hd = Arith.mul(wd, height);
            hd = Arith.round(hd,0); /* 四舍五入保留小数点0位 */
            h = Integer.parseInt(
            		String.valueOf(hd).substring(0
            				, String.valueOf(hd).indexOf("."))
            		) ; /* 高度应缩放到的尺寸 */
        }
        /*
        System.out.println("w  "+w);
        System.out.println("h  "+h);
        System.out.println("width  "+width);
        System.out.println("height  "+height);
        */
        /**
         * 如果按比例缩放的高大于指定的宽度则以高度为准则计算缩放的宽度
         */
        if(h>oh){ 
        	hd = Arith.div(oh, height, 10);
        	wd = Arith.mul(hd,width); /* 高度缩放比率乘以图片原始宽度=缩放后宽度 */
        	wd = Arith.round(wd,0);
            w = Integer.parseInt(
            		String.valueOf(wd).substring(0, String.valueOf(wd).indexOf("."))
            		) ; /* 按比例缩小高度 */
            h = oh;
        }
    	tag = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);  
        Graphics g = tag.getGraphics();
        g.drawImage(img, 0, 0, w, h, 0, 0, width, height, null);
        FileOutputStream out = new FileOutputStream(newFile); //输出到文件流  
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
        encoder.encode(tag); //JPEG编码 
        out.flush();
        out.close(); 
        str = newFile;	
        return str;
    }
    
    /**
     * 
     * @param w
     * @param h
     * @param oldFile
     * @param newFile
     * @return
     * @throws IOException
     */
    public String shrinkImage(int w, int h, String oldFile, String newFile) throws IOException 
    {
    	if(oldFile==null || oldFile.equals("")){
    		return null;
    	}
    	else if(w<1){
    		return null;
    	}
    	else{
	    	newFile = this.filePath + newFile;   	
	    	oldFile = this.filePath + oldFile;
	    	String str = this.shrinkImage(w,oldFile,newFile);
	        return str;
    	}
    }
    
    /*
    public static void main(String args[]){
    	ImageOperate io = new ImageOperate();
    	try {
			io.shrinkImage(70,"E:\\work\\MYJAVA\\newBox\\imageFolder\\200612\\logo.jpg"
					,"E:\\work\\MYJAVA\\newBox\\imageFolder\\200612\\logo2.jpg");
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    */

	public String getMessage(){
        return this.message;
    }
    public void setFilePath(String filePath){
        if(filePath!=null){
            this.filePath = filePath;
        }else{
            this.filePath = "";
        }
    }
    public void setStr(String str){
        if(str!=null){
            this.str = str;
        }else{
            this.str = "www.YeQiangWei.com";
        }
    }
    public void setWaterImg1(String str){
        if(str!=null){
            this.waterImg1 = str;
        }else{
            this.waterImg1 = "";
        }
    }
    public void setWaterImg2(String str){
        if(str!=null){
            this.waterImg2 = str;
        }else{
            this.waterImg2 = "";
        }
    }  
    public void setWaterPath(String str){
        if(str!=null){
            this.waterPath = str;
        }else{
            this.waterPath = "";
        }
    } 
    
    
}
